<template>
  <view class="container">
    <view class="conversation">
      <view v-for="(item,index) in data" :key="index" :class="['module','module-'+item.position]">
        <image v-if="item.position=='robot'&&headerRobotImg!=''" :class="['herder-image','header-'+item.position]"  :src="headerRobotImg"></image>
        <image v-if="item.position=='robot'&&headerRobotImg==''" :class="['herder-image','header-'+item.position]" src="../static/images/icon_header.png"></image>
        <view :class="['words','animated','fadeIn',item.position]" v-if="item.type!='image'">{{item.question}}</view>
         <view :class="['picture','animated','fadeIn',item.position]" v-else :data-url="item.question" @click="previewImage">
           <image
             :src="item.question"
             mode="scaleToFill"
             lazy-load="false">
           </image>
         </view>
        <image mode='widthFix' v-if="item.position=='user'&&userHeaderImage==''" :class="['herder-image','header-'+item.position]"  src="../static/images/icon_header.png"></image>
        <image mode='widthFix'  v-if="item.position=='user'&&userHeaderImage!=''" :class="['herder-image','header-'+item.position]"  :src="userHeaderImage"></image>
      </view>
    </view>
    <view class="chat-box" :style='{"bottom":slideDown?"0":"-300upx"}'>
      <view class="chat-bottom">
        <view>
          <input type="text" @input="onKeyInput" :model="sendText" @focus="onKeyFocus" :selection-start="cursor" :adjust-position="position" :focus='focus' :value="sendText">
        </view>
        <view class="button">
          <view class="send fadeIn" v-if="sendText.length>0" @click="sendContent">发送</view>
          <view class="add fadeOut" v-else @click="sildeDown">
             <image
               src="../static/images/icon-add.png"
               mode="scaleToFill"
               lazy-load="false">
             </image>
          </view>
        </view>
      </view>
      <view :class="['slide-down',slideDown?'drawer-up':'drawer-down']">
          <view class="item" data-type="album" @click="chooseImage">
            <image
              src="../static/images/icon_album.png"
              mode="scaleToFill"
              lazy-load="false">
            </image>
          </view>
          <view class="item" data-type="camera" @click="chooseImage">
             <image
              src="../static/images/icon_camera.png"
              mode="scaleToFill"
              lazy-load="false">
            </image>
          </view>
      </view>
    </view>
  </view>
</template>
<script>
import { setTimeout } from 'timers';
import Vue from "vue"
import InterServer from "@/common/config/server";
import {localStorageSyncServer} from "@/common/js/common"
import {API} from "@/common/config/config"
let socketOpen = false;
let SocketTask = false;
export default {
  data() {
    return {
      headerRobotImg:"",  //用户画像
      userHeaderImage:"", //自己画像
      hostIp:Vue.globalData.hostIp,
      calendar: false,
      delay: 700,
      scrollTop: 0,
      sendText: "",
      slideDown:false,
      cursor:20,
      focus:false, //是否聚焦
      position:true,
      cuid:"",
      uid:"",
      pageNum:0,
      pageSize:100,
      hostIp:Vue.globalData.hostIp,
      data: [
        {
          position: "robot",
          question: "你好，欢迎您来到平台在线服务；您可以在线咨询您的问题"
        }
      ],
    };
  },
  onLoad(options) {
    let _that=this
    if(options){
       _that.cuid=options.id,
       _that.uid=Vue.globalData.userInfo.userInfoId
		   _that.userHeaderImage=Vue.globalData.userInfo.image==undefined ? "" : Vue.globalData.userInfo.image
       _that.reg=/\/.*?(gif|png|jpg|JPG|jpeg|raw|heic)/gi
    }
    this.headerRobotImg=localStorageSyncServer.get("herderRobotImg")==undefined ? "" :localStorageSyncServer.get("herderRobotImg").indexOf("https")==0 ? localStorageSyncServer.get("herderRobotImg") : this.hostIp+localStorageSyncServer.get("herderRobotImg")
    console.log("headerRo"+this.herderRobotImg)
     setTimeout(function(){
        _that.pageScrollTo()
     },500)
  },
  onShow(){
    let cuid=this.cuid
    // #ifdef H5
        document.title=`在线服务`
     //let url=`ws://192.168.0.107:8080/ws/im?uid=${this.uid}&cuid=${cuid}`;
     let url=`ws://zadai.net:8000/ws/im?uid=${this.uid}&cuid=${cuid}`;
   // #endif
    //#ifdef APP-PLUS
      let url=`ws://zadai.net:8000/ws/im?uid=${this.uid}&cuid=${cuid}`;
    // #endif
     console.log(url)
     SocketTask = uni.connectSocket({
      url: url,
      data: {},
      header: {
        'content-type': 'application/json'
      },
      method: 'get',
      success: function (res) {
        console.log('WebSocket连接创建', res)
      },
      fail: function (err) {
        uni.showToast({
          title: '网络异常！',
        })
        console.log(err)
      },
    })
    if (SocketTask) {
      SocketTask.onOpen(res => {
        console.log('监听 WebSocket 连接打开事件。', res)
      })
      SocketTask.onClose(onClose => {
        console.log('监听 WebSocket 连接关闭事件。', onClose)
      })
      SocketTask.onError(onError => {
        console.log('监听 WebSocket 错误。错误信息', onError)
      })
      SocketTask.onMessage(onMessage => {
        console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', onMessage)
        let res=JSON.parse(onMessage.data)
        console.log(res)
        if(res.fromId==-2){
        //   uni.showToast({
        //     title: '对方已下线',
        //     duration: 3000,
        //     icon:"none"
        // });
        }else{
          if(res.text!=""&&res.fromId==this.cuid){
            if(res.text.match(this.reg)){
               this.data.push({
                  position: "robot",
                  type:"image",
                  question:this.hostIp+res.text
                })
            }else{
              this.data.push({
                position: "robot",
                question: res.text
              })
            }
          }
          this.pageScrollTo()
        }
       
      })
    }
    this.getHistoryMessage()  //获取历史消息
  },
  methods: {
    //实现定时
    timeout() {
      let _that = this;
      return new Promise(resolve => {
        setTimeout(resolve, _that.delay);
      });
    },
    //问题输入
    onKeyInput(e) {
      this.sendText=e.detail.value
    },
    //选取照片和照相机
    sildeDown(){
      setTimeout(()=>{
        this.slideDown=!this.slideDown
      },300)
    },
    //获取焦点
    onKeyFocus(e){
      if(e.type=="focus"){
          this.slideDown=false;
      }
    },
    //发送内容
    sendContent(){
      var data={};
      data["fromId"]=this.uid;
      data["fromName"]="";
      data["toId"]=this.cuid;
      data["text"]=this.sendText;
      SocketTask.send({
        data: JSON.stringify(data),
        success:(res=>{
          console.log("发送成功")
          console.log(res)
          this.data.push({
            position: "user",
            question: this.sendText
          })
        })
      })
      this.sendText="";
      this.pageScrollTo()
    },
    //获取聊天信息
    getHistoryMessage(){
      let _that=this
      _that.data.length=0
      InterServer.getHistoryMessage({
        pageNum:this.pageNum,
        pageSize:this.pageSize,
        uid:this.cuid
      }).then(res=>{
          if(res.code==200){
            res.data.dataList.reverse().forEach(item => {
              if(item.fromId==_that.uid){
                if(item.text.match(_that.reg)){
                    _that.data.push({
                      position: "user",
                      type:"image",
                      question: _that.hostIp+item.text
                    })
                }else{
                  _that.data.push({
                   position: "user",
                   question: item.text
                 })
                }
              }else{
                 if(item.text.match(_that.reg)){
                    _that.data.push({
                      position: "robot",
                      type:"image",
                      question: _that.hostIp+item.text
                    })
                  }else{
                    this.data.push({
                    position: "robot",
                    question: item.text
                  })
                }
              }
            });
          }
        // setTimeout(function(){
        //   _that.pageScrollTo()
        // })
      })
    },
    //页面滚动到置顶位置
    pageScrollTo(){
       let _that = this;
      const query = uni.createSelectorQuery();
      query.selectAll(".conversation").boundingClientRect();
      query.exec(function(res) {
        setTimeout(()=>{
           uni.pageScrollTo({
            scrollTop: res[0][0].height,
            duration: 100
          })
        },0)
      });
    },
    
    //照片发送
		chooseImage(e,callFn){
        let sourceType=e.currentTarget.dataset.type
        let _that=this;
				uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: [sourceType], //album从相册选择-camera相机拍摄
				success:(res)=>{
          //回调函数实现图片上传
          	uni.uploadFile({
                  url: API.uploadImgChat,
                  filePath:res.tempFilePaths[0], 
                  name: 'file',
                  success: (uploadFileRes) => {
                      _that.data.push({
                        position: "user",
                        type:"image",
                        // #ifdef H5
                        question: '/uploads'+JSON.parse(uploadFileRes.data).data,
                        // #endif
                        //#ifdef APP-PLUS
                        question: this.hostIp+'/uploads'+JSON.parse(uploadFileRes.data).data
                          // #endif
                      })
                      let data={};
                      data["fromId"]=_that.uid;
                      data["fromName"]="";
                      data["toId"]=_that.cuid;
                      data["text"]='/uploads'+JSON.parse(uploadFileRes.data).data;
                      SocketTask.send({
                        data: JSON.stringify(data),
                        success:(res=>{
                          console.log(JSON.parse(uploadFileRes.data).data)
                        })
                      })
                  }
              });
          setTimeout(function(){
            _that.pageScrollTo() 
            _that.slideDown=false;
          },1000)

        } 
			});
		},  
    //点击预览图片
    previewImage(e){
      console.log(e)
      uni.previewImage({
          urls: [e.currentTarget.dataset.url]
      });

    },
    
   
    //回答问题
  }
};
</script>


<style lang="less" scoped>
uni-page-body {
    background: #f4f4f4;
    height: 100%;
}
.container {
  @robot-bg-color: #ffffff;
  @robot-ft-color: #333333;
  @user-bg-color: #0057d9;
  @user-ft-color: #ffffff;
  font-size: 30upx;
  margin: 0 30upx;
  position: relative;
  height: 100%;
  .conversation{
    height: auto;
    clear: both;
    &::after {
      content: '';
      display: block;
      clear: both;
}
  }
  .module {
    display: flex;
    .herder-image{
      width:80upx;
      height:80upx;
      border-radius: 50%;
    }
    .header-robot{
      margin:15upx 20upx 15upx 0
    }
    .header-user{
      margin:15upx 0upx 15upx 20upx
    }
    img {
      margin-top: 20upx;
      width: 80upx;
      height: 80upx;
    }
    &-user {
      float: right;
      clear: both;
    }
    &-robot {
      clear: both;
    }
    &:last-child{
      margin-bottom: 300upx;
    }
  }
  .words {
    position: relative;
    display: inline-block;
    line-height: 50upx;
    max-width: 600upx;
    word-wrap: break-word;
    word-break: break-all;
    text-align: left;
    margin: 15upx 0upx;
    padding: 15upx 30upx;
    border-radius: 10upx;
    background: @user-bg-color;
  }
  .picture{
      position: relative;
      
      image{
        width: 200upx;
        height: 280upx;
        border-radius: 10upx;
      }
  }
  .robot {
    background: @robot-bg-color;
    color: @robot-ft-color;
  }
  .user {
    color: @user-ft-color;
    float: right;
  }
  .robot::after,
  .words::after {
    position: absolute;
    content: "";
    top: 27upx;
    left: -10upx;
    width: 0upx;
    height: 0upx;
    display: block;
    border-top: 14upx solid transparent;
    border-bottom: 14upx solid transparent;
    border-right: 14upx solid @robot-bg-color;
  }
  .words:after {
    border-right: 14upx solid @robot-bg-color;
  }
  .user:after {
    left: auto;
    right: -10upx;
    border-right: 0upx;
    border-left: 14upx solid @user-bg-color;
  }
  .fadeIn-enter-active {
    animation: fade-in 0.5s;
  }
  .fadeIn-leave-active {
    animation: fade-in 0.5s reverse;
  }
  @keyframes fade-in {
    0% {
      transform: scale(0);
    }
    50% {
      transform: scale(1.5);
    }
    100% {
      transform: scale(1);
    }
  }
  .clear {
    background: none;
    border: 0;
    clear: both;
    display: block;
    float: none;
    font-size: 0;
    margin: 0;
    padding: 0;
    overflow: hidden;
    visibility: hidden;
    width: 0;
    height: 0;
  }
  .chat-box{
    width: 100%;
    height: 400upx;
    position: fixed;
    left: 0;
    bottom:-300upx;
    transition: all 0.2s ease-out;
    transform: translateY(0);
    .chat-bottom {
      display: flex;
      height: 100upx;
      background: #f7f7f7;
      border-top: 1upx solid #dddddd;
      align-items: center;
      align-content: center;
      padding: 0 20upx;
      input {
        height: 80upx;
        border: 1upx solid #dddddd;
        border-radius: 10upx;
        width: 580upx;
        background: #ffffff;
        line-height: 80upx;
        padding: 0 20upx;
      }
      .button {
        margin-left: 20upx;
        .send {
          width: 100upx;
          height: 75upx;
          background: #0057d9;
          color: #ffffff;
          text-align: center;
          line-height: 75upx;
          color: #ffffff;
          font-size: 28upx;
          border-radius: 10upx;
        }
        .add {
          width: 100upx;
          height: 70upx;
          border-radius: 50%;
          text-align: center;
          font-weight: bold;
          font-size: 50upx;
          display: flex;
          align-items: center;
          justify-content: center;
          image{
            width:70upx;
            height:70upx;
          }
        }
      }
    }
    .slide-down{
      transition: all 0s ease-out;
      transform: translateY(100%);
      display: flex;
      height: 300upx;
      padding: 30upx;
      background: #f7f7ff;
      .item{
        background: #ffffff;
        border-radius: 10upx;
        margin-right: 20upx;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100upx;
        height: 100upx;
        image{
          width: 64upx;
          height: 64upx;
        }
      }
    }

    .drawer-up{
      height: 300upx;
      transform: translateY(0);
    }
    .drawer-down{
      transform: translateY(100%);
      overflow: hidden;
    }
  }

}
</style>
